import { Button, message, Modal, Space } from 'ant-design-vue'
import moment from 'moment'
import { defineComponent, nextTick, onMounted, ref } from 'vue'
import { useRouter } from 'vue-router'

import { userApi } from '@/apis'
import qzyApi from '@/apis/qzyApi'
import { ProTable, ProTableProps, ProTableRef } from '@/components'
import { TABLE_FORMAT, TABLE_ITEM_RENDER, TABLE_RENDERER } from '@/constants'
import { bus, optionsToMap } from '@/utils'

export default defineComponent({
  name: 'QzyLotteryManage',
  setup() {
    const router = useRouter()
    const modalId = ref('')
    const visible = ref(false)
    const statusOptions = [
      { label: '未开始', value: 0 },
      { label: '进行中', value: 1 },
      { label: '已结束', value: 2 }
    ]
    const statusMap = optionsToMap(statusOptions)
    const tableRef = ref({} as ProTableRef)
    const tableConfig = ref<ProTableProps>({
      fixedHeight: true,
      options: {
        border: true,
        align: 'center',
        toolbarConfig: {
          perfect: false,
          slots: {
            buttons: 'toolbarButtons'
          }
        },
        proxyConfig: {
          form: true,
          props: {
            result: 'records',
            total: 'total'
          },
          ajax: {
            query: async ({ page, form }) => {
              const data = await qzyApi.getLotteryActivityList({
                pageSize: page.pageSize,
                pageNo: page.currentPage,
                ...form
              })
              return data
            }
          }
        },
        formConfig: {
          items: [
            {
              title: '活动名称',
              field: 'activityName',
              itemRender: {
                name: TABLE_ITEM_RENDER.AInput,
                props: {
                  placeholder: '请输入活动名称',
                  style: {
                    width: '200px'
                  }
                }
              }
            },
            {
              title: '活动时间',
              itemRender: {
                name: TABLE_RENDERER.FormItemDate,
                props: {
                  type: 'range',
                  placeholder: ['开始时间', '结束时间'],
                  valueFormat: 'x',
                  showTime: {
                    defaultValue: [
                      moment('00:00:00', 'HH:mm:ss'),
                      moment('23:59:59', 'HH:mm:ss')
                    ]
                  },
                  keys: ['startTime', 'endTime']
                }
              }
            },
            {
              title: '状态',
              field: 'activityStatus',
              itemRender: {
                name: TABLE_ITEM_RENDER.ASelect,
                props: {
                  placeholder: '全部',
                  allowClear: true
                },
                options: statusOptions
              }
            },
            {
              itemRender: {
                name: TABLE_RENDERER.FormItemBtns
              }
            }
          ]
        },
        columnConfig: {
          minWidth: 100,
          resizable: true
        },
        columns: [
          {
            title: '活动名称',
            field: 'activityName'
          },
          {
            title: '活动开始时间',
            field: 'startTime',
            formatter: TABLE_FORMAT.Date
          },
          {
            title: '活动结束时间',
            field: 'endTime',
            formatter: TABLE_FORMAT.Date
          },
          {
            title: '状态',
            field: 'activityStatus',
            formatter: ({ cellValue }) => {
              return statusMap[cellValue]
            }
          },
          {
            title: '创建时间',
            field: 'createTime',
            formatter: TABLE_FORMAT.Date
          },
          {
            title: '碎片总量',
            field: 'fragmentsTotal'
          },
          {
            title: '累计发放碎片',
            field: 'fragmentsSendTotal'
          },
          {
            title: '剩余碎片',
            field: 'fragmentsResidueTotal'
          },
          {
            title: '操作',
            fixed: 'right',
            slots: {
              default: 'operation'
            }
          }
        ],
        pagerConfig: {
          pageSize: 10
        }
      }
    })
    onMounted(() => {
      bus.on('refreshQzylotteryList', () => {
        nextTick(() => {
          tableRef.value.refresh()
        })
      })
    })
    //新增抽奖活动
    function handleCreate() {
      router.push('QzyLotteryEdit')
    }
    //查看详情
    function handleDetail(item) {
      router.push({
        name: 'QzyLotteryDetail',
        query: {
          id: item.activityId
        }
      })
    }
    //抽奖记录
    function handleRecord(item) {
      router.push({ name: 'QzyLotteryRecord', query: { id: item.activityId } })
    }
    //编辑
    function handleEdit(item) {
      router.push({ name: 'QzyLotteryEdit', query: { id: item.activityId } })
    }
    //库存日志
    function handleLog(item) {
      router.push({ name: 'QzyInventoryLog', query: { id: item.activityId } })
    }
    function handleModal(item) {
      visible.value = true
      modalId.value = item.activityId
    }
    async function finish() {
      try {
        await qzyApi
          .finishDrawActivity({ id: modalId.value })
          .then(() => message.success('已结束该活动'))
      } finally {
        visible.value = false
        tableRef.value.refresh()
      }
    }
    return {
      tableRef,
      visible,
      tableConfig,
      finish,
      handleModal,
      handleDetail,
      handleRecord,
      handleEdit,
      handleLog,
      handleCreate
    }
  },
  render() {
    return (
      <div>
        <ProTable
          ref="tableRef"
          v-slots={{
            operation: ({ row }) => (
              <div>
                <Button
                  type="link"
                  size="small"
                  onClick={() => this.handleEdit(row)}
                  v-show={row.activityStatus === 0}
                >
                  编辑
                </Button>
                <Button
                  type="link"
                  size="small"
                  onClick={() => this.handleDetail(row)}
                >
                  查看详情
                </Button>
                <Button
                  type="link"
                  size="small"
                  onClick={() => this.handleRecord(row)}
                >
                  抽奖记录
                </Button>
                <Button
                  type="link"
                  size="small"
                  onClick={() => this.handleLog(row)}
                >
                  库存日志
                </Button>
                <Button
                  type="link"
                  size="small"
                  onClick={() => this.handleModal(row)}
                  v-show={row.activityStatus === 1}
                >
                  结束活动
                </Button>
              </div>
            ),
            toolbarButtons: () => {
              return (
                <Space>
                  <Button
                    style={{ position: 'absolute', left: '10px', top: '5px' }}
                    type="primary"
                    onClick={this.handleCreate}
                  >
                    新增抽奖活动
                  </Button>
                </Space>
              )
            }
          }}
          {...this.tableConfig}
        />
        <Modal
          v-model:visible={this.visible}
          width={'300px'}
          bodyStyle={{ fontSize: '16px', fontWeight: 500 }}
          centered={true}
          onOk={this.finish}
        >
          确认结束当前活动吗？
        </Modal>
      </div>
    )
  }
})
